package com.example.nio.controller;

import com.example.nio.commons.Result;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@RestController
public class WxFileUploadCtrl {

	@Value("${wx.imag}")
	private String imagUrl;

	@PostMapping("/imagUpload")
	public Result doImgUpload(@RequestParam("file") MultipartFile file) throws IOException {
		File pfile = new File(imagUrl);
		if (!pfile.exists()) {
			pfile.mkdirs();
		}
		// 获取文件名
		String fileName = file.getOriginalFilename();
		// 获取文件后缀
		String prefix = fileName.substring(fileName.lastIndexOf("."));
		String filepath = imagUrl + UUID.randomUUID().toString().replaceAll("-", "") + prefix;
		File dofile = new File(filepath);
		if (dofile.exists()) {
			dofile.delete();
		}
		dofile.createNewFile();
		file.transferTo(dofile);

		return new Result<>().setData("/showPicture/" + dofile.getName());
	}
	@GetMapping("/showPicture/{filename}")
	public void showPicture(@PathVariable String filename, HttpServletResponse response) throws IOException {
		File file = new File(imagUrl + filename);
		FileInputStream inputStream = new FileInputStream(file);
		response.setContentType("application/octet-stream");
		FileCopyUtils.copy(inputStream,response.getOutputStream());
	}
}
